package com.guxuede.mina.codefactory;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.HashMap;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.guxuede.mina.bean.HttpMessage;


public class HttpDecoder extends CumulativeProtocolDecoder {

	private final Charset charset;

	public HttpDecoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	protected boolean doDecode(IoSession session, IoBuffer in,ProtocolDecoderOutput out) throws Exception {
		IoBuffer buffer = IoBuffer.allocate(100).setAutoExpand(true);
		CharsetDecoder cd = charset.newDecoder();

		
		String head="",uri="",data="";
		int matchCount = 0,br=0;
		while (in.hasRemaining()) {
			byte b = in.get();
			buffer.put(b);
			matchCount++;
			if(b=='\r' && br==0){
				br++;
				buffer.flip();
				head = buffer.getString(matchCount-1, cd);
				int from=head.indexOf(' ');
				int to1=head.lastIndexOf(' ');
				int to2=head.lastIndexOf('?');
				int to=to2==-1?to1:to2;
				uri=head.substring(from+1, to);
				data=to2==-1?"":head.substring(to2+1, to1);
				matchCount = 0;
				buffer.clear();
			}
		}
		HttpMessage message=new HttpMessage();
		message.head=head;
		message.uri=uri;
		message.data=parseData(data);
		out.write(message);
		return false;
	}

	public static HashMap<String,String> parseData(String data){
		HashMap<String,String> da=new HashMap<String,String>();
		String[] kv=data.split("&|=");
		for(int i=1;i<kv.length;i=i+2){
			try {
				da.put(kv[i-1], kv[i]);
			} catch (Exception e) {
				break;
			}
		}
		return da;
	}
}
